package com.pxxy.mall.auth.controller;

import com.pxxy.common.exception.BizCodeEnum;
import com.pxxy.common.utils.R;
import com.pxxy.mall.auth.constant.AuthServerConstant;
import com.pxxy.mall.auth.feign.MemberApi;
import com.pxxy.mall.auth.feign.ThirdPartyApi;
import com.pxxy.mall.auth.vo.UserLoginVo;
import com.pxxy.mall.auth.vo.UserRegistVo;
import com.pxxy.mall.auth.vo.UserRegVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author zhangjj
 * @since 2024/2/4
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartyApi thirdPartyApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberApi memberApi;


    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        //todo 接口防刷

        //2.验证码再次校验,60秒之内防止验证码频繁发送
        String code = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (code != null) {
            String s = code.split("_")[1];
            long time = Long.parseLong(s);
            if (System.currentTimeMillis() - time <= 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        R r = thirdPartyApi.sendCode(phone);
        String smsCode = (String) r.get("smsCode") + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, smsCode, 10, TimeUnit.MINUTES);
        return R.ok();
    }


    /**
     * 注册
     *
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegVo userRegVo, BindingResult result, RedirectAttributes attributes) {
        //如果有错误回到注册页面
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
        //判断验证码是否正确
        String codeNum = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegVo.getPhone());

        if (!StringUtils.isEmpty(codeNum)) {
            if (userRegVo.getCodeNum().equals(codeNum.split("_")[0])) {
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegVo.getPhone());
                UserRegistVo userRegistVo = new UserRegistVo();
                BeanUtils.copyProperties(userRegVo, userRegistVo);
                R r = memberApi.regist(userRegistVo);

                if (r.getCode() == 0) {
                    return "redirect:http://auth.mall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("data", (String) r.get("data"));
                    attributes.addFlashAttribute("errors", errors);

                    return "redirect:http://auth.mall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("codeNum", "验证码不正确");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.mall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("codeNum", "验证码不正确");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
    }

    /**
     *
     */

    @PostMapping("/login")
    public String login(@Valid UserLoginVo userLoginVo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(k -> k.getField(), v -> v.getDefaultMessage()));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/login.html";
        }
        R r = memberApi.login(userLoginVo);
        if (r.getCode() == 0) {
            Object user = r.get("user");
            System.out.println(user);
            return "redirect:http://mall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", (String) r.get("msg"));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/login.html";
        }
    }


}
